﻿using AhCha.Fortunate.Common.Cache;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace AhCha.Fortunate.Common.Utility
{
    public class WeChatUtil
    {
        const string Key = "access_token";

        /// <summary>
        /// 获取token
        /// </summary>
        /// <returns></returns>
        private static async Task<string> GetAccessTokenAsync()
        {
            if (MemoryCacheHelper.Exists(Key))
            {
                return MemoryCacheHelper.Get<string>(Key);
            }
            //读取环境变量  登录微信https://mp.weixin.qq.com 查看 AppId 和 AppSecret
            string AppId = Environment.GetEnvironmentVariable("AppId");
            string AppSecret = Environment.GetEnvironmentVariable("AppSecret");
            if (string.IsNullOrWhiteSpace(AppId) || string.IsNullOrWhiteSpace(AppSecret))
            {
                throw Oops.Oh("系统环境变量未设置");
            }
            string url = $"https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={AppId}&secret={AppSecret}";
            var result = await HttpManager.HttpClientGetAsync(url);
            JObject obj = JObject.Parse(result);
            if (obj.ContainsKey(Key))
            {
                string token = obj[Key].ToString();
                MemoryCacheHelper.Set(Key, token, new TimeSpan(2, 0, 0));
                return token;
            }
            return "";
        }

        /// <summary>
        /// 发送操作
        /// </summary>
        /// <returns></returns>
        private static async Task<bool> SendWeChatMessageAsync(SendWeChatMessageInput input)
        {
            string ass_token = await GetAccessTokenAsync();
            if (!string.IsNullOrWhiteSpace(ass_token))
            {
                string url = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=" + ass_token;//小程序
                var result = await HttpManager.HttpClientPostJson(url, JsonConvert.SerializeObject(input));
                JObject obj = JObject.Parse(result);
                if (obj.ContainsKey("errmsg") && obj["errmsg"].ToString().Equals("ok", StringComparison.CurrentCultureIgnoreCase))
                {
                    return true;
                }
            }
            return false;
        }


        /// <summary>
        /// 发送微信订阅通知
        /// </summary>
        /// <param name="OpenId"></param>
        /// <returns></returns>
        public static async Task SendMessageAsync(string OpenId)
        {
            if (!string.IsNullOrWhiteSpace(OpenId))
            {
                //登录微信https://mp.weixin.qq.com  查看模板id
                //相应的模板格式在订阅信息中可查看
                await SendWeChatMessageAsync(new SendWeChatMessageInput()
                {
                    template_id = "",
                    page = "",
                    touser = OpenId,
                    data = new
                    {
                        thing1 = new
                        {
                            value = "数值",
                        },
                        thing3 = new
                        {
                            value = "数值",
                        },
                    }
                });
            }

        }


        /// <summary>
        /// 批量发送微信订阅通知
        /// </summary>
        /// <param name="OpenIds">必填项【微信】接收者的openid集合</param>
        /// <param name="BatchSizeFactor">根据实体数量计算每个批次的大小，默认1/4</param>
        /// <returns></returns>
        public static async Task BatchSendMessageAsync(List<string> OpenIds, int BatchSizeFactor = 4)
        {
            if (OpenIds is not null && OpenIds.Count > 0)
            {
                int TaskSize = Math.Max(1, OpenIds.Count / BatchSizeFactor);
                for (int i = 0; i < OpenIds.Count; i += TaskSize)
                {
                    var batch = OpenIds.Skip(i).Take(TaskSize).ToList();
                    await Task.WhenAll(batch.Select(async OpenId => await SendMessageAsync(OpenId)));
                }
            }
        }


    }

    /// <summary>
    /// 订阅发送数据输入类
    /// </summary>
    public class SendWeChatMessageInput
    {
        /// <summary>
        /// 初始化部分数据
        /// </summary>
        public SendWeChatMessageInput()
        {
            miniprogram_state = "formal";
            lang = "zh_CN";
        }

        /// <summary>
        /// 所需下发的订阅模板id
        /// </summary>
        public required string template_id { get; set; }

        /// <summary>
        /// 点击模板卡片后的跳转页面，仅限本小程序内的页面。支持带参数,（示例index?foo=bar）。该字段不填则模板无跳转
        /// </summary>
        public string? page { get; set; }

        /// <summary>
        /// 接收者（用户）的 openid
        /// </summary>
        public required string touser { get; set; }

        /// <summary>
        /// 模板内容，格式形如 { "key1": { "value": any }, "key2": { "value": any } }的object
        /// 相应的模板格式在订阅信息中查看
        /// </summary>
        public required object data { get; set; }

        /// <summary>
        /// 跳转小程序类型：developer为开发版；trial为体验版；formal为正式版；默认为正式版
        /// </summary>
        public string miniprogram_state { get; set; }

        /// <summary>
        /// 进入小程序查看”的语言类型，支持zh_CN(简体中文)、en_US(英文)、zh_HK(繁体中文)、zh_TW(繁体中文)，默认为zh_CN
        /// </summary>
        public string lang { get; set; }

    }
}
